import { defineEventHandler, createError } from 'h3';

const LIMIT = 60; // 每分钟 60 次
const ipMap = new Map();
const WINDOW = 60 * 1000; // 1 分钟

export default defineEventHandler((event) => {
	const ip = event.node.req.headers['x-forwarded-for'] || event.node.req.connection.remoteAddress;
	const now = Date.now();
	if (!ipMap.has(ip)) ipMap.set(ip, []);
	const times = ipMap.get(ip).filter((t: number) => now - t < WINDOW);
	times.push(now);
	ipMap.set(ip, times);
	if (times.length > LIMIT) {
		throw createError({ statusCode: 429, statusMessage: '请求过于频繁' });
	}
});
